﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace TfsUtils
{
    public  class AssemblyNumbering
    {
        public Workspace Workspace { get; set; }

        public String Path { get; set; }

        public AssemblyNumbering(Workspace workspace, string path)
        {
            Workspace = workspace;
            Path = path;
        }

        /// <summary>
        /// Grab the owner of theworkspace and handle all the stuff needed to 
        /// create and manage the xml.
        /// </summary>
        /// <returns></returns>
        private Int16 ForOwner()
        {
            XmlUtils xmlUtils = new XmlUtils(Path);
            var ownerId = xmlUtils.GetIdForValue(Workspace.OwnerName, "Owner");
            //use the ownerid in the file assembly numbering
            if (xmlUtils.UpdateRequired)
            {
                //need to update data file.
                String filename = xmlUtils.GetFileNameForCategory("Owner");
                if (!File.Exists(filename))
                {
                    xmlUtils.Save();
                    Workspace.PendAdd(filename);
                }
                else
                {
                    Workspace.PendEdit(filename);
                    xmlUtils.Save();
                }
                var pendingChanges = Workspace.GetPendingChanges(filename);
                Workspace.CheckIn(pendingChanges, "***NO_CI***");
            }
            return (Int16) ownerId;
        }

        public  void Generate(String filename, Int16 major, Int16 minor, Int16 build, String revision)
        {
            short revisionReal = GetRealId(revision);
            File.WriteAllText(filename, String.Format(
                @"
                //Autogenerated by a tool, do not modify
                [assembly: AssemblyFileVersion(""{0}.{1}.{2}.{3}"")]",
                major, minor, build, revisionReal));
        }

        private short GetRealId(string requestedToken)
        {
            Int16 revisionReal = 0;
            if (requestedToken.IndexOf("owner", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                revisionReal = ForOwner();
            }
            return revisionReal;
        }
    }
}
